import { useAuth } from 'context/auth-context'
import React from 'react'
import { Form, Input } from 'antd'
import { LongButton } from 'unauthenticated-app'
import { useAsync } from 'utils/use-async'

// TS是鸭子类型(duck typing)：面向接口编程 而不是 面向对象编程
export const LoginPage = ({ onError }: { onError: ( error: Error ) => void }) => {
  const {login} = useAuth()
  // 此处没有传入error是因为这里运用了同步与异步混用
  // 如果使用error，当异步任务开始时同步任务也开始，这样error就拿不到本次异步任务的错误，而是要等异步任务完成
  const { run, isLoading } = useAsync(undefined, { throwOnError: true });
  
  const handleSubmit = async (values: {username: string; password: string}) => {
    try {
      await run(login(values))
    }catch(e:any){
      onError(e)
    }
  }

  return (
    <Form onFinish={handleSubmit}>
      <Form.Item name={'username'} rules={[{required: true, message: '请输入用户名'}]}>
        <Input placeholder={'用户名'} type="text" id={'username'} />
      </Form.Item>
      <Form.Item name={'password'} rules={[{required: true, message: '请输入密码'}]}>
        <Input placeholder={'密码'} type="password" id={'password'} />
      </Form.Item>
      <Form.Item >
        <LongButton loading={isLoading} htmlType={'submit'} type={'primary'}>登录</LongButton>
      </Form.Item>
    </Form>
  )
}
